package com.karileet.nokia.meeting.profile;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.util.Log;


public class DataInputOutput {
	/**
	 * Method stores "input" to "file"
	 * 
	 * @param String
	 *            file File name to store into
	 * @param String
	 *            input Input to store
	 * @param Context
	 *            ctx Calling context
	 * @return boolean
	 */
	public static boolean saveToMemory(String file, String input, Context ctx) {
		Log.d(MainActivity.APP, "Starting 'saveToMemory' method with file: "
				+ file + " and input: " + input);
		boolean retval = false;
		FileOutputStream fos;
		try {
			fos = ctx.openFileOutput(file, Context.MODE_PRIVATE);
			fos.write(input.getBytes());
			fos.close();
			retval = true;
		} catch (Exception e) {
			Log.e(MainActivity.APP,
					"Unable to read from file! " + e.getMessage());
		}
		return retval;
	}

	/**
	 * Method reads data from "file" and returns it. Buffer is 100 bytes and it
	 * is cleaned from empty chars before returning
	 * 
	 * @param String
	 *            file File to read from
	 * @param Context
	 *            ctx Calling context
	 * @return String Contents of the file
	 */
	public static String readFromMemory(String file, Context ctx) {
		Log.d(MainActivity.APP, "Starting 'readFromMemory' method. File: "
				+ file);
		FileInputStream fis;
		StringBuffer tone = new StringBuffer("");
		byte[] buffer = new byte[100];
		try {
			fis = ctx.openFileInput(file);
			while (fis.read(buffer) != -1) {
				tone.append(new String(buffer));
			}
			fis.close();
		} catch (Exception e) {
			Log.e(MainActivity.APP,
					"Unable to read from file! " + e.getMessage());
		}
		String emptyChars = tone.toString();
		return emptyChars.replaceAll("\u0000.*", "");
	}
}
